package com.design.twords.utils;

import android.util.Log;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Create by Alen
 * Time:  1:30
 */
public class FanyiV3Yd {
    private static final String YOUDAO_URL = "https://openapi.youdao.com/api";

    private static final String APP_KEY = "3c6004629ad9e8b5";

    private static final String APP_SECRET = "9NnIHe9Izzbf5pEs07Jndb9HGHAwWPYF";

    public static void requestForYoudao(String word,final CallBackListener callBackListener){

        String salt = String.valueOf(System.currentTimeMillis());
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String sign = APP_KEY + truncate(word) + salt + curtime + APP_SECRET;

        RequestBody formbody = new FormBody.Builder()
                .add("q",word)
                .add("form", "en")
                .add("to", "zh-CHS")
                .add("appKey", APP_KEY)
                .add("salt", salt)
                .add("sign", getDigest(sign))
                .add("signType", "v3")
                .add("curtime", curtime)
                .build();

        Request request = new Request.Builder()
                .post(formbody)
                .url(YOUDAO_URL)
                .build();

        OkHttpClient client = new OkHttpClient();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("tag","fail_to_search");
                        callBackListener.onFailure(call,e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("tag","success");
                        callBackListener.onResponse(call,response);
                        //JsonForOcr.analyseJson(response.body().string());

                    }
                });


    }
    /**
     * 生成加密字段
     */
    public static String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("SHA-256");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
    public static String truncate(String q) {
        if (q == null) {
            return null;
        }
        int len = q.length();
        String result;
        return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len));
    }


}
